#!/bin/bash

cur_dir=$(cd "$(dirname "$0")";pwd)

check()
{
    sec=0
    runFlag=0
    while (($sec <= 60))
    do
        sec=$[sec + 5]
        if [[ $runFlag == 1 ]]
        then
            break;
        fi
        echo "masterServer checking ..."
        oldpid=$(ps -ef | grep masterServer | grep -v grep | awk '{print $2}')
        if [[ $oldpid != "" ]]
        then
            runFlag=1
            echo "masterServer is running, pid is $oldpid"
            continue
        fi

        cd $cur_dir
        export LD_LIBRARY_PATH=/usr/local/lib
        $cur_dir/masterServer -c $cur_dir/conf/master.conf > /dev/null 2>&1 &
        ret=$?
        pid=$(ps -ef | grep masterServer | grep -v grep | awk '{print $2}')
        if [[ $pid != "" ]] && [[ $ret == "0" ]]
        then
            echo "masterServer start success! pid is $pid"
            runFlag=1
        else
            echo "masterServer start failed, restart again! return is $ret"
        fi
    done
}

case $1 in
    check)
        check
    ;;
esac